package org.abettor.nookinfo.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.persist.PhotoHelper;
import org.abettor.nookinfo.photo.PhotoCategory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

/**
 * 图片更新工作定时启动器
 * @author shawn
 *
 */
public class PhotoUpdateReceiver extends BroadcastReceiver
{
	public static final String NOTIFICATION_TAG = "org.abettor.nookinfo.photo";
	private static final int TIME_OUT = 60 * 60 * 1000;
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private Context context;
	private PhotoHelper photoHelper;
	private NotificationManager notiMgm;

	@Override
	public void onReceive(Context context, Intent intent)
	{
		//	每次闹钟响了，就再设置一次
		registerReceiverAlarm(context);

		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		if(hour <= 6 || hour >= 21)
		{
			return;
		}

		//	初始化持久功能对象和通知对象
		this.context = context;
		photoHelper = new PhotoHelper(context);
		notiMgm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

		//	检查更新
		try
		{
			checkUpdate();
		}
		catch(Exception e)
		{
			Log.d(this.getClass().getName(), "", e);
		}
	}

	/**
	 * 注册系统定时器，以便定时执行
	 */
	public static void registerReceiverAlarm(Context context)
	{
		Intent intent = new Intent(context, PhotoUpdateReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + TIME_OUT, pi);
	}

	//	检查图片更新
	private void checkUpdate() throws Exception
	{
		//	获取远程Category列表
		List<PhotoHelper.PhotoCategory> categoryList = fetchCategories();

		//	获取本地Category集合
		List<PhotoHelper.PhotoCategory> localCategoryList = photoHelper.getCategoryList();
		Map<Integer, PhotoHelper.PhotoCategory> map = new HashMap<Integer, PhotoHelper.PhotoCategory>();
		for(PhotoHelper.PhotoCategory pc : localCategoryList)
		{
			map.put(pc.id, pc);
		}

		//	对比每个Category的时间，发现更新并通知
		for(PhotoHelper.PhotoCategory pc : categoryList)
		{
			PhotoHelper.PhotoCategory lpc = map.get(pc.id);
			if(lpc == null)
			{
				//	发现更新，提示
				updateNotify();
				return;
			}

			if(lpc.update.before(pc.update))
			{
				//	发现更新，提示
				updateNotify();
				return;
			}
		}
	}

	//	更新提示
	private void updateNotify()
	{
		Intent activityIntent = new Intent();
		activityIntent.setClass(context, PhotoCategory.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, activityIntent, 0);

		Notification noti = new Notification(android.R.drawable.stat_notify_sync, context.getString(R.string.photo_category_update), System.currentTimeMillis());
		noti.setLatestEventInfo(context, context.getString(R.string.photo_category_update_title), context.getString(R.string.photo_category_update_content), pendingIntent);
		noti.defaults |= Notification.DEFAULT_LIGHTS;
		noti.defaults |= Notification.DEFAULT_SOUND;

		notiMgm.cancel(NOTIFICATION_TAG, 0);
		notiMgm.notify(NOTIFICATION_TAG, 0, noti);
	}

	//	读取图片分类信息
	private List<PhotoHelper.PhotoCategory> fetchCategories() throws Exception
	{
		List<PhotoHelper.PhotoCategory> categoryList = new ArrayList<PhotoHelper.PhotoCategory>();
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(AddressConstant.PHOTO_CATEGORY);
		NodeList list = doc.getElementsByTagName("category");
		int len = list.getLength();
		for(int i = 0; i < len; i ++)
		{
			PhotoHelper.PhotoCategory item = new PhotoHelper.PhotoCategory();
			Node node = list.item(i);
			NodeList nodes = node.getChildNodes();
			int count = nodes.getLength();
			for(int j = 0; j < count; j ++)
			{
				//	只要关注id和update就行了
				Node itemNode = nodes.item(j);
				String nodeName = itemNode.getNodeName();
				if("id".equals(nodeName))
				{
					String id = itemNode.getTextContent();
					item.id = Integer.valueOf(id);
				}
				else if("update".equals(nodeName))
				{
					String update = itemNode.getTextContent();
					item.update = DATE_FORMAT.parse(update);
				}
			}

			categoryList.add(item);
		}

		return categoryList;
	}
}
